//
// Created by jinyf on 2022/3/2.
//

#ifndef INC_54_FFMPEG_MP3PLAYER_MNAUDIO_H
#define INC_54_FFMPEG_MP3PLAYER_MNAUDIO_H


#include "MNPlaystatus.h"
#include "MNCallJava.h"
#include "MNQueue.h"
#include "MNPlaystatus.h"

#include "SoundTouch.h"

extern "C"
{
#include "libavcodec/avcodec.h"
#include <libswresample/swresample.h>
#include <SLES/OpenSLES.h>
#include <SLES/OpenSLES_Android.h>
};


using namespace soundtouch;

class MNAudio {

public:
    int streamIndex = -1;
    AVCodecContext *avCodecContext = NULL;
    AVCodecParameters *codecpar = NULL;
    MNQueue *queue = NULL;

    MNPlaystatus *playstatus = NULL;
    int sample_rate = 0;

    const int channel=2;
    //16BIT
    const int bit=2;

    pthread_t openelsInitThread;

    AVPacket *avPacket = NULL;
    AVFrame *avFrame = NULL;
    int ret = 0;
    uint8_t *buffer = NULL;
    int data_size = 0;

    // 引擎接口
    SLObjectItf engineObject = NULL;
    SLEngineItf engineEngine = NULL;

    //混音器
    SLObjectItf outputMixObject = NULL;
    SLEnvironmentalReverbItf outputMixEnvironmentalReverb = NULL;
    SLEnvironmentalReverbSettings reverbSettings = SL_I3DL2_ENVIRONMENT_PRESET_STONECORRIDOR;


    //pcm
    SLObjectItf pcmPlayerObject = NULL;
    SLPlayItf pcmPlayerPlay = NULL;
    SLMuteSoloItf pcmMutePlay=NULL;
    SLVolumeItf pcmVolumePlay = NULL;

    //缓冲器队列接口
    SLAndroidSimpleBufferQueueItf pcmBufferQueue = NULL;


    //--------------------------------------
    //时长
    int duration;

    AVRational time_base;

    //当前frame时间
    double now_time;
    //当前实际播放时间
    double clock_time;

    double last_time;

    MNCallJava *callJava;


    //----------------------
    float speed=1.0f;
    
    SoundTouch *soundTouch=NULL;

    uint8_t *out_buffer=NULL;

    SAMPLETYPE *sampleBuffer=NULL;

//    波处理完了没
    bool finished = true;

//    新波的实际个数
    int nb = 0;
    int num = 0;

    float pitch=1.0f;

public:
    MNAudio(MNPlaystatus *pPlaystatus, int _sample_rate,MNCallJava *callJava);

    ~MNAudio();

    void play();

    void initOpenSLES();

    int resampleAudio(void **pVoid);
    int getCurrentSampleRateForOpensles(int sample_rate);

    void pause();

    void resume();

    void setMute(int i);

    void setVolume(int percent);

    void setSpeed(float d);

    int getSoundTouchData();

    void setPitch(float d);

    void release();
};


#endif //INC_54_FFMPEG_MP3PLAYER_MNAUDIO_H
